<?php
namespace app\admin\service;
use app\common\library\Service;
use think\Validate;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use think\Cache;

class Dysms extends Service
{
    protected function _initialize() {
        parent::_initialize();
    }

    /**
	* 发送验证码
	* @param string   $mobile      [接收手机号]
	* @param string   $content     [短信模板变量替换JSON串]
	* @param string   $tpl         [短信模板ID]
	* @return bool
	*/
	public function send($mobile = '', $params = '', $template_code = '', $scene = ''){
        /* 构造短信参数 */
        $config = config('dysms');
        $template_code = $template_code ?: $config['TemplateCode'];
        $scene = $scene ?: $template_code;

        if(empty($template_code)){
            $this->error = __('场景值不能为空');
            return false;
        }

        $cache = cache("member_sms_".$scene."_".$mobile);
        if($cache !== false) {
            $this->error = "请勿频繁提交";
            return false;
        }


        if(empty($params)) {
            $code = rand(100000, 999999);
            $params = [
                'code' => $code,
            ];
        }


        $sendSms = new SendSms;
        $sendSms->setPhoneNumbers($mobile)
                    ->setSignName($config['SignName'])
                    ->setTemplateCode($template_code)
                    ->setTemplateParam($params);
        /* 构造执行参数 */
        $client  = new Client($config);
        $result = $client->execute($sendSms);
        if($result->Code != "OK"){
            $this->error = $result->Message;
            return false;
        }
        cache("member_sms_".$scene."_".$mobile, $code, 60);
        return true;
	}

    /**
     * 短信验证
     * @param string $mobile    手机号
     * @param string $code      验证码
     * @param string $tpl       场景值
     * @param bool $is_destroy       成功后销毁
     * @return bool
     */
	public function check($mobile = '', $code = '', $scene = '', $is_destroy = false){
		$rule = [
            'mobile'	=> 'regex:/^1[34578]{1}[0-9]{9}$/',
        ];
        $msg = [
            'mobile.regex'	=> '手机号格式错误',
        ];
        $data = [
            'mobile'	=> $mobile,
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error = $validate->getError();
			return false;
        }
		if(empty($code)) {
			$this->error = __('验证码不能为空');
			return false;
		}
        $valid = cache("member_sms_".$scene."_".$mobile);

        if (empty($valid)) {
        	$this->error = __('验证码已过期，请重新获取');
            return false;
        }
		if ($valid != $code){
			$this->error = __('验证码错误');
			return false;
		}
		if ($is_destroy === true) {
            cache("member_".$scene."_".$mobile, null);
		}
        return true;
	}
}
